/*
 * Copyright (c) 2011 Anthony Vandikas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "stdafx.h"
#include "HistoryWidget.h"

#include "AbstractHistory.h"
#include "HistoryModel.h"

HistoryWidget::HistoryWidget(AbstractHistory &history) 
	: history(&history), model(new HistoryModel(history, DateColumn | StudentColumn | ItemColumn))
{
	ui.setupUi(this);
	ui.entryView->setModel(model);

	// There's no way to get a QDateEdit to default to the current day, so it has to be set manually.
	ui.fromDate->setDate(QDate::currentDate());
	ui.toDate->setDate(QDate::currentDate());
}

HistoryWidget::~HistoryWidget()
{
	delete model;
}

void HistoryWidget::filterChanged()
{
	auto minDate = ui.fromDate->date();
	auto maxDate = ui.toDate->date();
	auto studentKeywords = ui.studentBox->text().split(' ', QString::SkipEmptyParts);
	auto itemKeywords = ui.itemBox->text().split(' ', QString::SkipEmptyParts);

	model->filter(minDate, maxDate, studentKeywords, itemKeywords);
}

void HistoryWidget::fromDateChanged()
{
	// This (and toDateChanged) ensures that the dates don't overlap.
	if (ui.fromDate->date() > ui.toDate->date())
		ui.toDate->setDate(ui.fromDate->date());
}

void HistoryWidget::toDateChanged()
{
	if (ui.toDate->date() < ui.fromDate->date())
		ui.fromDate->setDate(ui.toDate->date());
}

void HistoryWidget::resetClicked()
{
	ui.toDate->setDate(QDate::currentDate());
	ui.fromDate->setDate(QDate::currentDate());
	ui.studentBox->clear();
	ui.itemBox->clear();
}
